<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />

    

    
    <title>【React深入】setState的执行机制 | 李世奇的技术专栏</title>
    
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
        <meta name="keywords" content="React" />
    
    <meta name="description" content="一.几个开发中经常会遇到的问题以下几个问题是我们在实际开发中经常会遇到的场景，下面用几个简单的示例代码来还原一下。 1.setState是同步还是异步的，为什么有的时候不能立即拿到更新结果而有的时候可以?1.1 钩子函数和React合成事件中的setState现在有两个组件 componentDidMount() &amp;#123;  console.log(&apos;parent componentDidM">
<meta name="keywords" content="React">
<meta property="og:type" content="article">
<meta property="og:title" content="【React深入】setState的执行机制">
<meta property="og:url" content="https://www.lisq.xyz/2019/03/06/【React深入】setState的执行机制/index.html">
<meta property="og:site_name" content="李世奇的技术专栏">
<meta property="og:description" content="一.几个开发中经常会遇到的问题以下几个问题是我们在实际开发中经常会遇到的场景，下面用几个简单的示例代码来还原一下。 1.setState是同步还是异步的，为什么有的时候不能立即拿到更新结果而有的时候可以?1.1 钩子函数和React合成事件中的setState现在有两个组件 componentDidMount() &amp;#123;  console.log(&apos;parent componentDidM">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://www.lisq.xyz/img/setstate.jpg">
<meta property="og:updated_time" content="2019-04-06T05:27:16.846Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【React深入】setState的执行机制">
<meta name="twitter:description" content="一.几个开发中经常会遇到的问题以下几个问题是我们在实际开发中经常会遇到的场景，下面用几个简单的示例代码来还原一下。 1.setState是同步还是异步的，为什么有的时候不能立即拿到更新结果而有的时候可以?1.1 钩子函数和React合成事件中的setState现在有两个组件 componentDidMount() &amp;#123;  console.log(&apos;parent componentDidM">
<meta name="twitter:image" content="https://www.lisq.xyz/img/setstate.jpg">
    

    

    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/titillium-web/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    


</head>


<body>
    <div id="wrap">
        <header id="header">
    <div id="header-outer" class="outer">
        <div class="container">
            <div class="container-inner">
                <div id="header-title">
                    <h1 class="logo-wrap">
                        <a href="/" class="logo"></a>
                    </h1>
                    
                </div>
                <div id="header-inner" class="nav-container">
                    <a id="main-nav-toggle" class="nav-icon fa fa-bars"></a>
                    <div class="nav-container-inner">
                        <ul id="main-nav">
                            
                                <li class="main-nav-list-item" >
                                    <a class="main-nav-list-link" href="/">主页</a>
                                </li>
                            
                                        
                                    
                                <li class="main-nav-list-item" >
                                    <a class="main-nav-list-link" href="https://mp.weixin.qq.com/s/dYZEHTgqvxGV7mL99JuxRQ">关于</a>
                                </li>
                            
                                <li class="main-nav-list-item" >
                                    <a class="main-nav-list-link" href="https://github.com/ConardLi/ConardLi.github.io">更新日志</a>
                                </li>
                            
                                <li class="main-nav-list-item" >
                                    <a class="main-nav-list-link" href="/me/navigation.html">index.导航</a>
                                </li>
                            
                        </ul>
                        <nav id="sub-nav">
                            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>
        <div class="container">
            <div class="main-body container-inner">
                <div class="main-body-inner">
                    <section id="main">
                        <div class="main-body-header">
    <h1 class="header">
    
    未分类
    </h1>
</div>

                        <div class="main-body-content">
                            <style>
    #article-toc.fixed {
        position: fixed;
        top: 30px;
        bottom: 30px;
        left: 32px;
        padding-top: 15px;
        z-index: 9999;
        background-color: antiquewhite;
        width: 200px;
        padding-left: 20px;
        padding-bottom: 30px;
        border-radius: 10px;
        border: 1px solid rgb(122, 122, 122);
        opacity: 0.8;
    }

    #article-toc-inner {
        padding: 10px;
        width: 200px;
        height: 100%;
        overflow: auto;
    }

    .toc-level-3 {
        margin-left: 20px;
    }

    #article-toc a {
        text-decoration: none;
        color: #333;
        padding: 3px 0;
        color: #000;
        font-weight: normal;
    }

    .toc-item {
        line-height: 30px;
        list-style-type: initial;
    }

    #tocbtn {
        position: fixed;
        top: 30%;
        left: 0px;
        padding: 5px 2px;
        width: 18px;
        word-wrap: break-word;
        background-color: rgb(242, 245, 247);
        box-shadow: rgba(118, 118, 118, 0.11) 2px 0px 5px 0px;
        opacity: 1;
        height: 94px;
        line-height: 16px;
        text-align: center;
        top: 33%;
        width: 30px;
        z-index: 1000000001;
        cursor: pointer;
        border-radius: 0px 4px 4px 0px;
        border-width: 1px 1px 1px;
        border-style: solid solid solid none;
        border-color: rgb(224, 228, 231) rgb(224, 228, 231) rgb(224, 228, 231);
        border-image: initial;
        border-left: none;
        padding: 6px;
        transition: right 0.4s ease-in 0.3s, opacity 0.5s ease-in 0.3s;
    }
</style>

<article id="post-【React深入】setState的执行机制"
    class="article article-single article-type-post"
    itemscope itemprop="blogPost">
    <div class="article-inner">
        
        <header class="article-header">
            
    
        <h1 class="article-title" itemprop="name">
        【React深入】setState的执行机制
        </h1>
    

        </header>
        
        
        <div class="article-meta">
            
    <div class="article-date">
        <a href="/2019/03/06/【React深入】setState的执行机制/" class="article-date">
            <time datetime="2019-03-06T08:12:35.000Z" itemprop="datePublished">2019-03-06</time>
        </a>
    </div>

            

            
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/React/">React</a>
    </div>

            <span id="busuanzi_container_page_pv" style="position: relative;float: right;">
                本文总阅读量<span id="busuanzi_value_page_pv"></span>次
            </span>
        </div>
        
        
        <div class="article-entry" itemprop="articleBody">
            <p><img src="/img/setstate.jpg" alt="image"></p>
<h1 id="一-几个开发中经常会遇到的问题"><a href="#一-几个开发中经常会遇到的问题" class="headerlink" title="一.几个开发中经常会遇到的问题"></a>一.几个开发中经常会遇到的问题</h1><p>以下几个问题是我们在实际开发中经常会遇到的场景，下面用几个简单的示例代码来还原一下。</p>
<h2 id="1-setState是同步还是异步的，为什么有的时候不能立即拿到更新结果而有的时候可以"><a href="#1-setState是同步还是异步的，为什么有的时候不能立即拿到更新结果而有的时候可以" class="headerlink" title="1.setState是同步还是异步的，为什么有的时候不能立即拿到更新结果而有的时候可以?"></a>1.setState是同步还是异步的，为什么有的时候不能立即拿到更新结果而有的时候可以?</h2><h3 id="1-1-钩子函数和React合成事件中的setState"><a href="#1-1-钩子函数和React合成事件中的setState" class="headerlink" title="1.1 钩子函数和React合成事件中的setState"></a>1.1 钩子函数和React合成事件中的<code>setState</code></h3><p>现在有两个组件</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">componentDidMount() &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'parent componentDidMount'</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">render() &#123;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">      &lt;SetState2&gt;&lt;/SetState2&gt;</span><br><span class="line">      &lt;SetState&gt;&lt;/SetState&gt;</span><br><span class="line">    &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>
<p>组件内部放入同样的代码，并在<code>Setstate1</code>中的<code>componentDidMount</code>中放入一段同步延时代码，打印延时时间：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">componentWillUpdate() &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'componentWillUpdate'</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">componentDidUpdate() &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'componentDidUpdate'</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">componentDidMount() &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'SetState调用setState'</span>);</span><br><span class="line">  <span class="keyword">this</span>.setState(&#123;</span><br><span class="line">    index: <span class="keyword">this</span>.state.index + <span class="number">1</span></span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'state'</span>, <span class="keyword">this</span>.state.index);</span><br><span class="line">  </span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'SetState调用setState'</span>);</span><br><span class="line">  <span class="keyword">this</span>.setState(&#123;</span><br><span class="line">    index: <span class="keyword">this</span>.state.index + <span class="number">1</span></span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'state'</span>, <span class="keyword">this</span>.state.index);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面是执行结果：</p>
<p><img src="https://user-gold-cdn.xitu.io/2019/2/23/169197bbda942d55?w=332&amp;h=337&amp;f=png&amp;s=37749" alt="image"></p>
<p>说明：</p>
<ul>
<li>1.调用<code>setState</code>不会立即更新</li>
<li>2.所有组件使用的是同一套更新机制，当所有组件<code>didmount</code>后，父组件<code>didmount</code>，然后执行更新</li>
<li>3.更新时会把每个组件的更新合并，每个组件只会触发一次更新的生命周期。</li>
</ul>
<h3 id="1-2-异步函数和原生事件中的setstate？"><a href="#1-2-异步函数和原生事件中的setstate？" class="headerlink" title="1.2 异步函数和原生事件中的setstate？"></a>1.2 异步函数和原生事件中的<code>setstate</code>？</h3><p>在<code>setTimeout</code>中调用<code>setState</code>（例子和在浏览器原生事件以及接口回调中执行效果相同）<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">componentDidMount() &#123;</span><br><span class="line">  setTimeout(() =&gt; &#123;</span><br><span class="line">    console.log(&apos;调用setState&apos;);</span><br><span class="line">    this.setState(&#123;</span><br><span class="line">      index: this.state.index + 1</span><br><span class="line">    &#125;)</span><br><span class="line">    console.log(&apos;state&apos;, this.state.index);</span><br><span class="line">    console.log(&apos;调用setState&apos;);</span><br><span class="line">    this.setState(&#123;</span><br><span class="line">      index: this.state.index + 1</span><br><span class="line">    &#125;)</span><br><span class="line">    console.log(&apos;state&apos;, this.state.index);</span><br><span class="line">  &#125;, 0);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>执行结果：</p>
<p><img src="https://user-gold-cdn.xitu.io/2019/2/23/169197bbda86af04?w=244&amp;h=219&amp;f=png&amp;s=20237" alt="image"></p>
<p>说明：</p>
<ul>
<li>1.在父组件<code>didmount</code>后执行</li>
<li>2.调用<code>setState</code>同步更新</li>
</ul>
<h2 id="2-为什么有时连续两次setState只有一次生效？"><a href="#2-为什么有时连续两次setState只有一次生效？" class="headerlink" title="2.为什么有时连续两次setState只有一次生效？"></a>2.为什么有时连续两次<code>setState</code>只有一次生效？</h2><p>分别执行以下代码：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">componentDidMount() &#123;</span><br><span class="line">  <span class="keyword">this</span>.setState(&#123; <span class="attr">index</span>: <span class="keyword">this</span>.state.index + <span class="number">1</span> &#125;, () =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.index);</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="keyword">this</span>.setState(&#123; <span class="attr">index</span>: <span class="keyword">this</span>.state.index + <span class="number">1</span> &#125;, () =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.index);</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">componentDidMount() &#123;</span><br><span class="line">  <span class="keyword">this</span>.setState(<span class="function">(<span class="params">preState</span>) =&gt;</span> (&#123; <span class="attr">index</span>: preState.index + <span class="number">1</span> &#125;), () =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.index);</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="keyword">this</span>.setState(<span class="function"><span class="params">preState</span> =&gt;</span> (&#123; <span class="attr">index</span>: preState.index + <span class="number">1</span> &#125;), () =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.index);</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">1</span><br><span class="line">1</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">2</span><br><span class="line">2</span><br></pre></td></tr></table></figure>
<p>说明：</p>
<ul>
<li>1.直接传递对象的<code>setstate</code>会被合并成一次</li>
<li>2.使用函数传递<code>state</code>不会被合并</li>
</ul>
<h1 id="二-setState执行过程"><a href="#二-setState执行过程" class="headerlink" title="二.setState执行过程"></a>二.setState执行过程</h1><p>由于源码比较复杂，就不贴在这里了，有兴趣的可以去<code>github</code>上<code>clone</code>一份然后按照下面的流程图去走一遍。</p>
<h2 id="1-流程图"><a href="#1-流程图" class="headerlink" title="1.流程图"></a>1.流程图</h2><p><img src="https://user-gold-cdn.xitu.io/2019/2/23/169197bbdc7ae14e?w=982&amp;h=2387&amp;f=png&amp;s=147606" alt="setState"></p>
<ul>
<li><code>partialState</code>：<code>setState</code>传入的第一个参数，对象或函数</li>
<li><code>_pendingStateQueue</code>：当前组件等待执行更新的<code>state</code>队列</li>
<li><code>isBatchingUpdates</code>：react用于标识当前是否处于批量更新状态，所有组件公用</li>
<li><code>dirtyComponent</code>：当前所有处于待更新状态的组件队列</li>
<li><code>transcation</code>：react的事务机制，在被事务调用的方法外包装n个<code>waper</code>对象，并一次执行：<code>waper.init</code>、被调用方法、<code>waper.close</code></li>
<li><code>FLUSH_BATCHED_UPDATES</code>：用于执行更新的<code>waper</code>，只有一个<code>close</code>方法</li>
</ul>
<h2 id="2-执行过程"><a href="#2-执行过程" class="headerlink" title="2.执行过程"></a>2.执行过程</h2><p>对照上面流程图的文字说明，大概可分为以下几步：</p>
<ul>
<li>1.将setState传入的<code>partialState</code>参数存储在当前组件实例的state暂存队列中。</li>
<li>2.判断当前React是否处于批量更新状态，如果是，将当前组件加入待更新的组件队列中。</li>
<li>3.如果未处于批量更新状态，将批量更新状态标识设置为true，用事务再次调用前一步方法，保证当前组件加入到了待更新组件队列中。</li>
<li>4.调用事务的<code>waper</code>方法，遍历待更新组件队列依次执行更新。</li>
<li>5.执行生命周期<code>componentWillReceiveProps</code>。</li>
<li>6.将组件的state暂存队列中的<code>state</code>进行合并，获得最终要更新的state对象，并将队列置为空。</li>
<li>7.执行生命周期<code>componentShouldUpdate</code>，根据返回值判断是否要继续更新。</li>
<li>8.执行生命周期<code>componentWillUpdate</code>。</li>
<li>9.执行真正的更新，<code>render</code>。</li>
<li>10.执行生命周期<code>componentDidUpdate</code>。</li>
</ul>
<h1 id="三-总结"><a href="#三-总结" class="headerlink" title="三.总结"></a>三.总结</h1><h2 id="1-钩子函数和合成事件中："><a href="#1-钩子函数和合成事件中：" class="headerlink" title="1.钩子函数和合成事件中："></a>1.钩子函数和合成事件中：</h2><p>在<code>react</code>的生命周期和合成事件中，<code>react</code>仍然处于他的更新机制中，这时<code>isBranchUpdate</code>为true。</p>
<p>按照上述过程，这时无论调用多少次<code>setState</code>，都会不会执行更新，而是将要更新的<code>state</code>存入<code>_pendingStateQueue</code>，将要更新的组件存入<code>dirtyComponent</code>。</p>
<p>当上一次更新机制执行完毕，以生命周期为例，所有组件，即最顶层组件<code>didmount</code>后会将<code>isBranchUpdate</code>设置为false。这时将执行之前累积的<code>setState</code>。</p>
<h2 id="2-异步函数和原生事件中"><a href="#2-异步函数和原生事件中" class="headerlink" title="2.异步函数和原生事件中"></a>2.异步函数和原生事件中</h2><p>由执行机制看，<code>setState</code>本身并不是异步的，而是如果在调用<code>setState</code>时，如果<code>react</code>正处于更新过程，当前更新会被暂存，等上一次更新执行后在执行，这个过程给人一种异步的假象。</p>
<p>在生命周期，根据JS的异步机制，会将异步函数先暂存，等所有同步代码执行完毕后在执行，这时上一次更新过程已经执行完毕，<code>isBranchUpdate</code>被设置为false，根据上面的流程，这时再调用<code>setState</code>即可立即执行更新，拿到更新结果。</p>
<h2 id="3-partialState合并机制"><a href="#3-partialState合并机制" class="headerlink" title="3.partialState合并机制"></a>3.<code>partialState</code>合并机制</h2><p>我们看下流程中<code>_processPendingState</code>的代码，这个函数是用来合并<code>state</code>暂存队列的，最后返回一个合并后的<code>state</code>。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line">_processPendingState: <span class="function"><span class="keyword">function</span> (<span class="params">props, context</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> inst = <span class="keyword">this</span>._instance;</span><br><span class="line">  <span class="keyword">var</span> queue = <span class="keyword">this</span>._pendingStateQueue;</span><br><span class="line">  <span class="keyword">var</span> replace = <span class="keyword">this</span>._pendingReplaceState;</span><br><span class="line">  <span class="keyword">this</span>._pendingReplaceState = <span class="literal">false</span>;</span><br><span class="line">  <span class="keyword">this</span>._pendingStateQueue = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (!queue) &#123;</span><br><span class="line">    <span class="keyword">return</span> inst.state;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (replace &amp;&amp; queue.length === <span class="number">1</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> queue[<span class="number">0</span>];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> nextState = _assign(&#123;&#125;, replace ? queue[<span class="number">0</span>] : inst.state);</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = replace ? <span class="number">1</span> : <span class="number">0</span>; i &lt; queue.length; i++) &#123;</span><br><span class="line">    <span class="keyword">var</span> partial = queue[i];</span><br><span class="line">    _assign(nextState, <span class="keyword">typeof</span> partial === <span class="string">'function'</span> ? partial.call(inst, nextState, props, context) : partial);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> nextState;</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>
<p>我们只需要关注下面这段代码：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">_assign(nextState, <span class="keyword">typeof</span> partial === <span class="string">'function'</span> ? partial.call(inst, nextState, props, context) : partial);</span><br></pre></td></tr></table></figure>
<p>如果传入的是对象，很明显会被合并成一次：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="built_in">Object</span>.assign(</span><br><span class="line">  nextState,</span><br><span class="line">  &#123;<span class="attr">index</span>: state.index+ <span class="number">1</span>&#125;,</span><br><span class="line">  &#123;<span class="attr">index</span>: state.index+ <span class="number">1</span>&#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>如果传入的是函数，函数的参数preState是前一次合并后的结果，所以计算结果是准确的。</p>
<h2 id="4-componentDidMount调用setstate"><a href="#4-componentDidMount调用setstate" class="headerlink" title="4.componentDidMount调用setstate"></a>4.<code>componentDidMount</code>调用<code>setstate</code></h2><blockquote>
<p>在componentDidMount()中，你 可以立即调用setState()。它将会触发一次额外的渲染，但是它将在浏览器刷新屏幕之前发生。这保证了在此情况下即使render()将会调用两次，用户也不会看到中间状态。谨慎使用这一模式，因为它常导致性能问题。在大多数情况下，你可以 在constructor()中使用赋值初始状态来代替。然而，有些情况下必须这样，比如像模态框和工具提示框。这时，你需要先测量这些DOM节点，才能渲染依赖尺寸或者位置的某些东西。</p>
</blockquote>
<p>以上是官方文档的说明，不推荐直接在<code>componentDidMount</code>直接调用<code>setState</code>，由上面的分析：<code>componentDidMount</code>本身处于一次更新中，我们又调用了一次<code>setState</code>，就会在未来再进行一次<code>render</code>，造成不必要的性能浪费，大多数情况可以设置初始值来搞定。</p>
<p>当然在<code>componentDidMount</code>我们可以调用接口，再回调中去修改<code>state</code>，这是正确的做法。</p>
<p>当state初始值依赖dom属性时，在<code>componentDidMount</code>中<code>setState</code>是无法避免的。</p>
<h2 id="5-componentWillUpdate-componentDidUpdate"><a href="#5-componentWillUpdate-componentDidUpdate" class="headerlink" title="5.componentWillUpdate componentDidUpdate"></a>5.<code>componentWillUpdate</code> <code>componentDidUpdate</code></h2><p>这两个生命周期中不能调用<code>setState</code>。</p>
<p>由上面的流程图很容易发现，在它们里面调用<code>setState</code>会造成死循环，导致程序崩溃。</p>
<h2 id="6-推荐使用方式"><a href="#6-推荐使用方式" class="headerlink" title="6.推荐使用方式"></a>6.推荐使用方式</h2><p>在调用<code>setState</code>时使用函数传递<code>state</code>值，在回调函数中获取最新更新后的<code>state</code>。</p>

        </div>
        <footer class="article-footer">
            



    <a data-url="https://www.lisq.xyz/2019/03/06/【React深入】setState的执行机制/" data-id="cjv0hxjy60003nh0d1lrlxwd4" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

        </footer>
    </div>
</article>


    <section id="comments">
    
        
    <div id="disqus_thread">
        <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    </div>

    
    </section>





<div id="roott"></div>

<button id="tocbtn">打开目录</button>


<script>
    var showToc = false;
    document.getElementById('tocbtn').onclick = function () {
        if (showToc) {
            document.getElementById('roott').innerHTML = ''
            document.getElementById('tocbtn').innerHTML = '打开目录'
        } else {
            document.getElementById('roott').innerHTML = `<aside id="article-toc" role="navigation" class="fixed">
  <div id="article-toc-inner">
    <strong class="sidebar-title">
      目录</strong>
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#一-几个开发中经常会遇到的问题"><span class="toc-text">一.几个开发中经常会遇到的问题</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-setState是同步还是异步的，为什么有的时候不能立即拿到更新结果而有的时候可以"><span class="toc-text">1.setState是同步还是异步的，为什么有的时候不能立即拿到更新结果而有的时候可以?</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-钩子函数和React合成事件中的setState"><span class="toc-text">1.1 钩子函数和React合成事件中的setState</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-异步函数和原生事件中的setstate？"><span class="toc-text">1.2 异步函数和原生事件中的setstate？</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-为什么有时连续两次setState只有一次生效？"><span class="toc-text">2.为什么有时连续两次setState只有一次生效？</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#二-setState执行过程"><span class="toc-text">二.setState执行过程</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-流程图"><span class="toc-text">1.流程图</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-执行过程"><span class="toc-text">2.执行过程</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#三-总结"><span class="toc-text">三.总结</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-钩子函数和合成事件中："><span class="toc-text">1.钩子函数和合成事件中：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-异步函数和原生事件中"><span class="toc-text">2.异步函数和原生事件中</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-partialState合并机制"><span class="toc-text">3.partialState合并机制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-componentDidMount调用setstate"><span class="toc-text">4.componentDidMount调用setstate</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-componentWillUpdate-componentDidUpdate"><span class="toc-text">5.componentWillUpdate componentDidUpdate</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-推荐使用方式"><span class="toc-text">6.推荐使用方式</span></a></li></ol></li></ol>
  </div>
</aside>`
            document.getElementById('tocbtn').innerHTML = '关闭目录'
        }
        showToc = !showToc;
    }
</script>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='//unpkg.com/valine/dist/Valine.min.js'></script>
<div id="vcomments" style="padding: 30px;"></div>
<script>
    new Valine({
        el: '#vcomments',
        appId: 's1xL54gwvPRsIy3ciItiPhyD-gzGzoHsz',
        appKey: 'CmP8stKpHUHtp5abbTxpqc4H'
    })
</script>
                        </div>
                    </section>
                    <aside id="sidebar">
    <a class="sidebar-toggle" title="Expand Sidebar"><i class="toggle icon"></i></a>
    <div class="sidebar-top">
        <p>
            关注我 :</p>
        <ul class="social-links">
            
            
            <li>
                <a class="social-tooltip" title="github" href="https://github.com/ConardLi"
                    target="_blank" rel="noopener">
                    <i class="icon fa fa-github"></i>
                </a>
            </li>
            
            
        </ul>
    </div>
    
    
<nav id="article-nav">
    
        <a href="/2019/03/06/【React深入】React事件机制/" id="article-nav-newer" class="article-nav-link-wrap">
        <strong class="article-nav-caption">下一篇</strong>
        <p class="article-nav-title">
        
            【React深入】React事件机制
        
        </p>
        <i class="icon fa fa-chevron-right" id="icon-chevron-right"></i>
    </a>
    
    
        <a href="/2018/12/28/【性能优化】前端性能优化总结/" id="article-nav-older" class="article-nav-link-wrap">
        <strong class="article-nav-caption">上一篇</strong>
        <p class="article-nav-title">前端性能优化总结</p>
        <i class="icon fa fa-chevron-left" id="icon-chevron-left"></i>
        </a>
    
</nav>

    
    <div class="widgets-container" style="background-color: #fff; border-right: 1px solid #e2e2e2;">
        
        
        
<div class="widget-wrap widget-list">
    <h3 class="widget-title">
        微信公众号
    </h3>
    <div class="widget">
        <img src="https://lsqimg-1257917459.cos-website.ap-beijing.myqcloud.com/gzh/qrcode.jpg" alt="">
    </div>
</div>

        
        

        
        
    <div class="widget-wrap">
        <h3 class="widget-title">最新文章</h3>
        <div class="widget">
            <ul id="recent-post" class="">
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2019/04/26/【自检】前端知识清单/" class="thumbnail">
    
    
        <span style="background-image:url(https://lsqimg-1257917459.cos.ap-beijing.myqcloud.com/blog/知识体系.png)" alt="【自检】前端知识清单" class="thumbnail-image"></span>
    
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"></p>
                            <p class="item-title"><a href="/2019/04/26/【自检】前端知识清单/" class="title">【自检】前端知识清单</a></p>
                            <p class="item-date"><time datetime="2019-04-26T01:11:22.000Z" itemprop="datePublished">2019-04-26</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2019/04/17/【React深入】深入分析虚拟DOM的渲染原理和特性/" class="thumbnail">
    
    
        <span style="background-image:url(https://lsqimg-1257917459.cos-website.ap-beijing.myqcloud.com/blog/react11.png)" alt="【React深入】深入分析虚拟DOM的渲染原理和特性" class="thumbnail-image"></span>
    
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"></p>
                            <p class="item-title"><a href="/2019/04/17/【React深入】深入分析虚拟DOM的渲染原理和特性/" class="title">【React深入】深入分析虚拟DOM的渲染原理和特性</a></p>
                            <p class="item-date"><time datetime="2019-04-17T03:15:27.000Z" itemprop="datePublished">2019-04-17</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2019/04/09/【React深入】从Mixin到HOC再到Hook/" class="thumbnail">
    
    
        <span style="background-image:url(https://lsqimg-1257917459.cos-website.ap-beijing.myqcloud.com/blog/hoc9.png)" alt="【React深入】从Mixin到HOC再到Hook" class="thumbnail-image"></span>
    
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"></p>
                            <p class="item-title"><a href="/2019/04/09/【React深入】从Mixin到HOC再到Hook/" class="title">【React深入】从Mixin到HOC再到Hook</a></p>
                            <p class="item-date"><time datetime="2019-04-09T15:27:27.000Z" itemprop="datePublished">2019-04-09</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2019/03/28/【浏览器和网络】全面分析前端的网络请求方式/" class="thumbnail">
    
    
        <span style="background-image:url(/img/network.jpg)" alt="全面分析前端的网络请求方式" class="thumbnail-image"></span>
    
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"></p>
                            <p class="item-title"><a href="/2019/03/28/【浏览器和网络】全面分析前端的网络请求方式/" class="title">全面分析前端的网络请求方式</a></p>
                            <p class="item-date"><time datetime="2019-03-28T12:38:59.000Z" itemprop="datePublished">2019-03-28</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2019/03/12/【前端工程】前端开发者必备的nginx知识/" class="thumbnail">
    
    
        <span style="background-image:url(/img/nginx.jpg)" alt="前端开发者必备的nginx知识" class="thumbnail-image"></span>
    
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"></p>
                            <p class="item-title"><a href="/2019/03/12/【前端工程】前端开发者必备的nginx知识/" class="title">前端开发者必备的nginx知识</a></p>
                            <p class="item-date"><time datetime="2019-03-12T06:50:35.000Z" itemprop="datePublished">2019-03-12</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

        
        
<div class="widget-wrap widget-list">
    <div class="">
        <h3 class="widget-title">标签</h3>
        <div class="widget widget-wrap-inn">
            <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/学习提升/">-学习提升</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript/">JavaScript</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/React/">React</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/electron/">electron</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nginx/">nginx</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/博客搭建/">博客搭建</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/性能优化/">性能优化</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/浏览器和网络/">浏览器和网络</a><span class="tag-list-count">1</span></li></ul>
        </div>
    </div>
</div>


<style>
    .widget-wrap-inn {
        background-color: white;
        padding: 10px;
        border-radius: 5px;
        border: 1px solid #ddd;
    }
</style>
        
        
<div class="widget-wrap widget-list">
    <h3 class="widget-title">归档</h3>
    <div class="widget  widget-wrap-inn">
        <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/04/">四月 2019</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/03/">三月 2019</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/12/">十二月 2018</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/11/">十一月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/01/">一月 2018</a><span class="archive-list-count">1</span></li></ul>
    </div>
</div>

        
        
<div class="widget-wrap widget-list">
    <h3 class="widget-title">友情链接</h3>
    <div class="widget  widget-wrap-inn">
        <ul>
            
            <li>
                <a href="https://juejin.im/user/5bea27965188250edf4ad8b7">掘金</a>
            </li>
            
            <li>
                <a href="https://segmentfault.com/u/conardli">segmentfault</a>
            </li>
            
            <li>
                <a href="https://github.com/ConardLi">github</a>
            </li>
            
            <li>
                <a href="https://github.com/ConardLi/tpanorama">tpanorama</a>
            </li>
            
            <li>
                <a href="http://chuangzaoshi.com/">创造狮导航</a>
            </li>
            
        </ul>
    </div>
</div>

        
        
<div class="widget-wrap widget-list">
    <!-- <h3 class="widget-title">
        腾讯云专属福利
    </h3> -->
    <div class="widget">
        <a target="_blank"
            href="https://cloud.tencent.com/redirect.php?redirect=1025&cps_key=1a3e7b07487819e129852ba7a4543262&from=console">
            <img src="/img/txy.jpg" id="txy" alt="">
        </a>
    </div>
</div>



<style>
    #txy {
        width: 280px;
        border: 5px;
    }
</style>
        
        
<div class="widget-wrap widget-list">
    <div class="widget">
        <a target="_blank" href="https://promotion.aliyun.com/ntms/act/qwbk.html?userCode=y3kv7eoj">
            <img src="/img/aly.png" id="txy" alt="">
        </a>
    </div>
</div>



<style>
    #txy {
        width: 280px;
        border: 5px;
    }
</style>
        
        
    </div>
</aside>
                </div>
            </div>
        </div>
        <footer id="footer">
    <div class="container">
        <div class="container-inner">
            <a id="back-to-top" href="javascript:;"><i class="icon fa fa-angle-up"></i></a>
            <div class="credit">
                <h1 class="logo-wrap">
                    <a href="/" class="logo"></a>
                </h1>
                <p>&copy;
                    2019
                    ConardLi
                </p>
                <p>Powered by <a href="//hexo.io/" target="_blank">Hexo</a>. Theme by <a href="//github.com/ppoffice"
                        target="_blank">ConardLi</a></p>
                <script type="text/javascript">
                    var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");
                    document.write(unescape("%3Cspan id='cnzz_stat_icon_1275088352'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s22.cnzz.com/z_stat.php%3Fid%3D1275088352%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));
                </script>
                <span id="busuanzi_container_site_pv" style="margin-left:50px;">
                    本站总访问量<span id="busuanzi_value_site_pv"></span>次
                </span>
                <span id="busuanzi_container_site_uv" style="margin-left:50px;">
                    本站访客数<span id="busuanzi_value_site_uv"></span>人次
                </span>
            </div>
            <div class="footer-plugins">
                
    


            </div>
        </div>
    </div>
</footer>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
        
    
    <script>
    var disqus_shortname = 'hexo-theme-hueman';
    
    
    var disqus_url = 'https://www.lisq.xyz/2019/03/06/【React深入】setState的执行机制/';
    
    (function() {
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.async = true;
    dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
    </script>




    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>

</html>